summaryrefslogtreecommitdiff
path: root/app/[lng]/partners/(partners)/swp-document-upload/vendor-document-page.tsx
blob: f8c6f1a72347d29d954df9e42a5491e85e4b3d9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { InfoIcon, Upload } from "lucide-react";
import { SwpTable } from "@/lib/swp/table/swp-table";
import { SwpInboxTable } from "@/lib/swp/table/swp-inbox-table";
import { SwpTableToolbar } from "@/lib/swp/table/swp-table-toolbar";
import {
  fetchVendorDocuments,
  fetchVendorProjects,
  fetchVendorSwpStats,
  getVendorSessionInfo,
  fetchVendorUploadedFiles,
} from "@/lib/swp/vendor-actions";
import type { DocumentListItem } from "@/lib/swp/document-service";
import type { SwpFileApiResponse } from "@/lib/swp/api-client";
import { toast } from "sonner";

interface VendorDocumentPageProps {
  searchParams: { [key: string]: string | string[] | undefined };
}

export default function VendorDocumentPage({ searchParams }: VendorDocumentPageProps) {
  // URL에서 프로젝트 번호만 사용 (나머지는 클라이언트 필터링)
  const initialProjNo = (searchParams.projNo as string) || "";

  // 상태 관리
  const [documents, setDocuments] = useState<DocumentListItem[]>([]);
  const [inboxFiles, setInboxFiles] = useState<SwpFileApiResponse[]>([]);
  const [requiredDocs, setRequiredDocs] = useState<Array<{ vendorDocNumber: string; title: string; buyerSystemComment: string | null }>>([]);
  const [projNo, setProjNo] = useState(initialProjNo);
  const [projects, setProjects] = useState<Array<{ PROJ_NO: string; PROJ_NM: string }>>([]);
  const [stats, setStats] = useState({
    total_documents: 0,
    total_revisions: 0,
    total_files: 0,
    uploaded_files: 0,
    last_sync: null as Date | null,
  });
  const [vendorInfo, setVendorInfo] = useState<{
    vendorId: number;
    vendorCode: string;
    vendorName: string;
    companyId: number;
  } | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 탭 상태
  const [activeTab, setActiveTab] = useState("inbox");

  // 클라이언트 필터
  const [searchFilters, setSearchFilters] = useState({
    docNo: (searchParams.docNo as string) || "",
    docTitle: (searchParams.docTitle as string) || "",
    pkgNo: (searchParams.pkgNo as string) || "",
    stage: (searchParams.stage as string) || "",
    status: (searchParams.status as string) || "",
  });

  // Dropzone 설정
  const [droppedFiles, setDroppedFiles] = useState<File[]>([]);

  // 파일 드롭 핸들러
  const onDrop = useCallback((acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      setDroppedFiles(acceptedFiles);
    }
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    noClick: true, // 클릭으로 파일 선택 비활성화 (버튼을 통해서만 선택)
    noKeyboard: true,
  });

  const loadInitialData = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      // 병렬로 데이터 로드
      const [vendorInfoData, projectsData] = await Promise.all([
        getVendorSessionInfo(),
        fetchVendorProjects(),
      ]);

      setVendorInfo(vendorInfoData);
      setProjects(projectsData);

      // 초기 프로젝트가 있으면 문서 로드
      if (initialProjNo) {
        const [documentsData, statsData, uploadedData] = await Promise.all([
          fetchVendorDocuments(initialProjNo),
          fetchVendorSwpStats(initialProjNo),
          fetchVendorUploadedFiles(initialProjNo),
        ]);
        setDocuments(documentsData);
        setStats(statsData);
        setInboxFiles(uploadedData.files);
        setRequiredDocs(uploadedData.requiredDocs);
      }
    } catch (err) {
      console.error("Failed to load initial data:", err);
      setError(err instanceof Error ? err.message : "Failed to load data");
      toast.error("Failed to load data");
    } finally {
      setIsLoading(false);
    }
  }, [initialProjNo]);

  const loadDocuments = useCallback(async () => {
    if (!projNo) return;

    try {
      setIsRefreshing(true);
      setError(null);

      const [documentsData, statsData, uploadedData] = await Promise.all([
        fetchVendorDocuments(projNo),
        fetchVendorSwpStats(projNo),
        fetchVendorUploadedFiles(projNo),
      ]);

      setDocuments(documentsData);
      setStats(statsData);
      setInboxFiles(uploadedData.files);
      setRequiredDocs(uploadedData.requiredDocs);
      toast.success("Document list refreshed");
    } catch (err) {
      console.error("Failed to load documents:", err);
      setError(err instanceof Error ? err.message : "Failed to load documents");
      toast.error("Failed to load documents");
    } finally {
      setIsRefreshing(false);
    }
  }, [projNo]);

  // 초기 데이터 로드
  useEffect(() => {
    loadInitialData();
  }, [loadInitialData]);

  // 프로젝트 변경 시 문서 재로드
  useEffect(() => {
    if (!isLoading && projNo) {
      loadDocuments();
    }
  }, [projNo, isLoading, loadDocuments]);

  const handleProjectChange = (newProjNo: string) => {
    setProjNo(newProjNo);
  };

  const handleFiltersChange = (filters: typeof searchFilters) => {
    setSearchFilters(filters);
  };

  const handleRefresh = () => {
    loadDocuments();
  };

  const handleUploadComplete = () => {
    // 업로드 완료 시 Inbox 탭으로 전환
    setActiveTab("inbox");
  };

  // 클라이언트 사이드 필터링 - VDR Documents
  const filteredDocuments = useMemo(() => {
    return documents.filter((doc) => {
      if (searchFilters.docNo && !doc.DOC_NO.toLowerCase().includes(searchFilters.docNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.docTitle && !doc.DOC_TITLE.toLowerCase().includes(searchFilters.docTitle.toLowerCase())) {
        return false;
      }
      if (searchFilters.pkgNo && !doc.PKG_NO?.toLowerCase().includes(searchFilters.pkgNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.stage && doc.STAGE !== searchFilters.stage) {
        return false;
      }
      if (searchFilters.status) {
        const statusLower = searchFilters.status.toLowerCase();
        const docStatus = doc.LTST_ACTV_STAT?.toLowerCase() || "waiting";
        if (!docStatus.includes(statusLower)) {
          return false;
        }
      }
      return true;
    });
  }, [documents, searchFilters]);

  // 클라이언트 사이드 필터링 - Inbox Files
  const filteredInboxFiles = useMemo(() => {
    return inboxFiles.filter((file) => {
      if (searchFilters.docNo && !file.OWN_DOC_NO.toLowerCase().includes(searchFilters.docNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.docTitle && !file.FILE_NM.toLowerCase().includes(searchFilters.docTitle.toLowerCase())) {
        return false;
      }
      if (searchFilters.pkgNo && !file.PKG_NO?.toLowerCase().includes(searchFilters.pkgNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.stage && file.STAGE !== searchFilters.stage) {
        return false;
      }
      if (searchFilters.status) {
        const statusLower = searchFilters.status.toLowerCase();
        const fileStatus = file.STAT_NM?.toLowerCase() || file.STAT?.toLowerCase() || "";
        if (!fileStatus.includes(statusLower)) {
          return false;
        }
      }
      return true;
    });
  }, [inboxFiles, searchFilters]);

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-4 w-96" />
        </CardHeader>
        <CardContent className="space-y-4">
          <Skeleton className="h-32 w-full" />
          <Skeleton className="h-96 w-full" />
        </CardContent>
      </Card>
    );
  }

  return (
    <div {...getRootProps()} className="relative w-full min-w-0">
      <input {...getInputProps()} />
      
      {/* 드래그 오버레이 */}
      {isDragActive && (
        <div className="fixed inset-0 z-50 bg-primary/20 backdrop-blur-sm flex items-center justify-center">
          <div className="bg-background border-2 border-dashed border-primary rounded-lg p-12 text-center space-y-4">
            <Upload className="h-16 w-16 mx-auto text-primary animate-bounce" />
            <div className="space-y-2">
              <p className="text-2xl font-semibold">Drop files here</p>
              <p className="text-muted-foreground">
                You can upload multiple files at once
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="space-y-6">
        {/* 에러 메시지 */}
        {error && (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {/* 통계 카드 */}
        {/* <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>할당된 문서</CardDescription>
              <CardTitle className="text-3xl">{stats.total_documents.toLocaleString()}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>총 리비전</CardDescription>
              <CardTitle className="text-3xl">{stats.total_revisions.toLocaleString()}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>총 파일</CardDescription>
              <CardTitle className="text-3xl">{stats.total_files.toLocaleString()}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>업로드한 파일</CardDescription>
              <CardTitle className="text-3xl text-green-600">
                {stats.uploaded_files.toLocaleString()}
              </CardTitle>
            </CardHeader>
          </Card>
        </div> */}

        {/* 안내 메시지 */}
        {documents.length === 0 && !projNo && (
          <Alert>
            <InfoIcon className="h-4 w-4" />
            <AlertDescription>
              Select a project to view assigned documents.
            </AlertDescription>
          </Alert>
        )}

        {/* 메인 테이블 - 탭 구조 */}
        <Card className="w-full overflow-hidden">
          <CardHeader>
            <SwpTableToolbar
              projNo={projNo}
              filters={searchFilters}
              onProjNoChange={handleProjectChange}
              onFiltersChange={handleFiltersChange}
              onRefresh={handleRefresh}
              onUploadComplete={handleUploadComplete}
              isRefreshing={isRefreshing}
              projects={projects}
              vendorCode={vendorInfo?.vendorCode}
              droppedFiles={droppedFiles}
              onFilesProcessed={() => setDroppedFiles([])}
              documents={filteredDocuments}
              userId={String(vendorInfo?.vendorId || "")}
              requiredDocs={requiredDocs}
            />
          </CardHeader>
          <CardContent>
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="inbox">
                  DOCUMENT REGISTRATION
                  {/* ({filteredInboxFiles.length}) */}
                </TabsTrigger>
                <TabsTrigger value="documents">
                  DOCUMENT LIST
                  {/* ({filteredDocuments.length}) */}
                </TabsTrigger>
              </TabsList>
              <TabsContent value="inbox" className="mt-4">
                <SwpInboxTable
                  files={filteredInboxFiles}
                  requiredDocs={requiredDocs}
                  projNo={projNo}
                  vendorCode={vendorInfo?.vendorCode || ""}
                  userId={String(vendorInfo?.vendorId || "")}
                />
              </TabsContent>
              <TabsContent value="documents" className="mt-4">
                <SwpTable
                  documents={filteredDocuments}
                  projNo={projNo}
                  vendorCode={vendorInfo?.vendorCode || ""}
                  userId={String(vendorInfo?.vendorId || "")}
                />
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}